#include "tcpclient.h"
#include <QDebug>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QNetworkInterface> // 用于获取IP，虽然这里固定了127.0.0.1

#include "databasemanager.h"

TcpClient::TcpClient(QObject *parent) : QObject(parent)
{


}

void TcpClient::openAllPort()
{
    DatabaseManager& dbManager = DatabaseManager::getInstance();

    if (!dbManager.connectMysql())
    {
        qDebug() << "COM打开数据库失败";
        return;
    }
    QSqlQuery query(dbManager.getDatabase());
    query.clear();
    query.prepare("SELECT port_no FROM port where protocol = 2");
    if (query.exec())
    {
        while (query.next())
        {
            ///////////////////需要修改成本地指定的端口连接到tcpServer
            // 处理查询结果
            int clientPort = query.value(0).toInt();
            QTcpSocket *tcpClient_socket = new QTcpSocket(this);
            this->tcpClients.insert(clientPort, tcpClient_socket);
            // 连接服务端
            QString ip = "127.0.0.1";
            quint16 ServerPort = 10009;
            tcpClient_socket->connectToHost(ip, ServerPort);
            connect(tcpClient_socket, &QTcpSocket::connected, [this, clientPort](){
                qDebug() << clientPort <<"已经成功连接到服务器";
            });
            connect(tcpClient_socket, &QTcpSocket::readyRead, this, &TcpClient::dealMsg);
            qDebug() << "tcpclient使用的端口" << clientPort;
        }
    }
}

void TcpClient::sendData(const int& clinetPort, const QByteArray &data)
{
    if (tcpClients.contains(clinetPort))
    {
        QTcpSocket *tcp_Socket = tcpClients.value(clinetPort);

        QString str = QString::fromLocal8Bit(data); // 保证发送的非ASCII码的中文能够打印出来
        qint64 bytesWritten = tcp_Socket->write(data);
        if (bytesWritten == -1) {
            qDebug() << "通过逻辑端口" << clinetPort << "发送数据失败: " << tcp_Socket->errorString();
        } else if (bytesWritten < data.size()) {
            emit sendDataFrom(clinetPort, data);
            qDebug() << "通过逻辑端口" << clinetPort << "发送数据不完整: " << bytesWritten << "/" << data.size() << "字节已发送。";
            // 这里可能需要处理未发送完的数据
        }
        else {
            // 需要将发送发的端口号和数据发送出去，从而能确定使用COM几
            emit sendDataFrom(clinetPort, data);
            qDebug() << "数据已通过逻辑端口" << clinetPort << "发送 ( " << bytesWritten << "字节): " << str/*data.toHex()*/;
            // socket->flush(); // 通常不需要立即 flush，Qt 会在事件循环中处理
        }

    }
}

void TcpClient::dealMsg()
{
    QTcpSocket *receivedSocket = qobject_cast<QTcpSocket*>(sender());
    if (receivedSocket) {
        QByteArray data = receivedSocket->readAll();

        QString str = QString::fromLocal8Bit(data); // 保证发送的非ASCII码的中文能够打印出来
        int logicalPort = -1;
        // Find the logical port (key) for this socket
        for (auto it = tcpClients.constBegin(); it != tcpClients.constEnd(); ++it) {
            if (it.value() == receivedSocket) {
                logicalPort = it.key();
                break;
            }

        }
        if (logicalPort != -1) {
            qDebug() << "端口" << logicalPort
                     << "收到数据:" << str/*data*/;//data.toHex()
            emit dataReceivedFromClient(logicalPort, data);
        } else {
            qDebug() << "错误：无法从sender()中找到TCP客户端的逻辑端口";
        }

//        qDebug() << "从逻辑端口" << receivedSocket
//                         << "(实际本地端口:" << receivedSocket->localPort()
//                         << ", 连接到服务器" << receivedSocket->peerAddress().toString() << ":" << receivedSocket->peerPort() << ")"
//                         << "收到数据:" << data.toHex() << "(原始: " << data << ")";

//        emit dataRecv(tcpClient->portName(), data);
    }
}

